import { v4 as uuid } from 'uuid';
import './interfaces';

function insert<T extends BaseTable>(tname: string, rowdata: T[]) {
	return rowdata.map((d) => {
		return {
			opflag: 4,
			rowdata: Object.assign({
				_id: uuid()
			}, d),
			tname
		} as ArgJsonInsert;
	});
}

function do_insert(systemid: string, argjson: ArgJsonInsert[]) {
	const msg = {
		argjson,
		spaceid,
		systemid
	};
	return send_msg('dbacc.save.intranet', msg) as Promise<{
		code: number;
		result: string;
	}>;
}

interface Table1 extends BaseTable {
	field1: string;
}

interface Table2 extends BaseTable {
	field2: string;
}

interface Message {
	tb1: Table1[];
	tb2: Table2[];
}

async function atom(msg: Message, headers: IHeaders) {
	const argjson1 = insert('@tablename1', msg.tb1);
	const argjson2 = insert('@tablename2', msg.tb2);
	const ret = await do_insert('@systemid', argjson1.concat(argjson2));
	if (ret.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
